package com.pilipili.sms.controller;

import com.pilipili.commonutils.Result;
import com.pilipili.sms.service.SmsService;
import com.pilipili.sms.utils.RandomUtil;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author 11826
 */
@RestController
@RequestMapping("/edusms")
public class SmsController {
    @Autowired
    private SmsService smsService;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @ApiOperation(value = "发送短信,设置有效时长")
    @GetMapping("send/{cellphoneNumber}")
    public Result sendMessage(@PathVariable String cellphoneNumber){
        String code = redisTemplate.opsForValue().get(cellphoneNumber);
        if(!StringUtils.isEmpty(code)){
            return Result.ok();
        }
        code= RandomUtil.getFourBitRandom();
        Map<String, Object> map = new HashMap<>();
        map.put("code",code);
        boolean isSend = smsService.send(cellphoneNumber,map);
        if(isSend){
            redisTemplate.opsForValue().set(cellphoneNumber,code,5,TimeUnit.MINUTES);//设置验证码有效时长
            return Result.ok();
        }else {
            return Result.error();
        }
    }
}
